package com.uzai.console.service.wechatapp.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.uzai.common.exception.BusinessException;
import com.uzai.console.entity.DeviceAppInfo;
import com.uzai.console.mapper.DeviceAppInfoMapper;
import com.uzai.console.service.wechatapp.AppDeviceInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author mingyang.chen create in 2023/5/29 11:13
 */
@Component
public class AppDeviceInfoServiceImpl implements AppDeviceInfoService {

    @Autowired
    private DeviceAppInfoMapper deviceAppInfoMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;


    @Override
    public DeviceAppInfo getByMerId(Long merId) {
        return deviceAppInfoMapper.selectByMerId(merId);
    }

    @Override
    public DeviceAppInfo init(Long merId) {

        Boolean success = redisTemplate.opsForValue().setIfAbsent("device_app_init_" + merId, merId, 1, TimeUnit.MINUTES);
        if (Boolean.FALSE.equals(success)) {
            throw new BusinessException("APP初始化操作频繁");
        }

        long deviceUniqueId = IdUtil.getSnowflakeNextId();

        DeviceAppInfo deviceAppInfo = new DeviceAppInfo();
        deviceAppInfo.setId(deviceUniqueId);
        deviceAppInfo.setMerId(merId);
        deviceAppInfo.setDeviceId(RandomUtil.randomString(32));
        deviceAppInfo.setDeviceName("内置机器人");
        deviceAppInfo.setDeviceRemark("内置机器人-备注");
        deviceAppInfo.setDelStatus(0);
        deviceAppInfo.setConfigRule(0);
        deviceAppInfo.setCreateTime((int) (System.currentTimeMillis() / 1000L));
        deviceAppInfo.setUpdateTime((int) (System.currentTimeMillis() / 1000L));

        deviceAppInfoMapper.insert(deviceAppInfo);
        return deviceAppInfo;
    }

    @Override
    public Boolean update(DeviceAppInfo deviceAppInfo) {
        deviceAppInfo.setUpdateTime((int) (System.currentTimeMillis() / 1000L));
        deviceAppInfoMapper.update(deviceAppInfo);
        return true;
    }
}
